package com.framework.file.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.io.ByteStreams;
import com.framework.file.dto.SysFileDto;
import com.framework.file.model.SysFile;
import com.framework.file.repository.SysFileRepository;
import com.framework.file.service.ISysFileService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.util.TimeZone;

@Api(tags = {"在线编辑接口"})
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)  //跨域请求
@RequestMapping(value = {"onlyoffice"})
@Slf4j
public class OnlyOfficeController {
    @Autowired
    private ISysFileService sysFileService;
    @Autowired
    private SysFileRepository sysFileRepository;

    /**
     * 在线编辑器回调操作
     */
    @RequestMapping(path = "/editCallBack", method = {RequestMethod.POST, RequestMethod.GET})
    public void editCallBack(HttpServletRequest request, HttpServletResponse response) throws Exception {
        PrintWriter writer = response.getWriter();
        Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\\A");
        String body = scanner.hasNext() ? scanner.next() : "";
        JSONObject jsonObj = JSONObject.parseObject(body);
        log.info("在线编辑器回调参数：{}", jsonObj);
        String userId = request.getParameter("userId");
        String fileId = request.getParameter("fileId");
        String downUrl = (String) jsonObj.get("url"); //保存变更后文件
        String changeTime = (String) jsonObj.get("lastsave");//修改时间
        if ((Integer) jsonObj.get("status") == 2) {
            //退出后自动保存-只在退出编辑后产生一份文件
            try {
                this.saveChange(downUrl, fileId, userId, changeTime);
            } catch (Exception e) {
                log.info("保存回调文件出错：{}", e.getMessage());
            }
        } else if ((Integer) jsonObj.get("status") == 6) {
            //手动保存-每点一次保存就产生一份新文件
            try {
                this.saveChange(downUrl, fileId, userId, changeTime);
            } catch (Exception e) {
                log.info("保存回调文件出错：{}", e.getMessage());
            }
        }

        writer.write("{\"error\":0}");
    }

    /**
     * @param downUrl    保存变更后文件
     * @param fileId
     * @param userId
     * @param changeTime 修改时间
     * @throws Exception
     */
    public void saveChange(String downUrl, String fileId, String userId, String changeTime) throws Exception {
        //todo 保留历史文件 通过中间表去关联业务和文件
        SysFile file = sysFileRepository.findOne(fileId);
        URL url = new URL(downUrl);
        InputStream inputStream = null;
        HttpURLConnection connection = null;
        try {
            file.setUpdaterId(userId);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date parse = simpleDateFormat.parse(changeTime);
            file.setUpdateTime(parse);

            SysFileDto dto = new SysFileDto();
            BeanUtils.copyProperties(file, dto);
            //新版文件
            connection = (HttpURLConnection) url.openConnection();
            InputStream ins = connection.getInputStream();
            byte[] byteArray = ByteStreams.toByteArray(ins);
            dto.setData(byteArray);

            sysFileService.upload(dto);
        } finally {
            if (null != inputStream) {
                inputStream.close();
            }
            if (null != connection) {
                connection.disconnect();
            }
        }

    }
}
